package com.kzc.controller;

import com.kzc.base.model.Result;
import com.kzc.service.MemberService;
import com.kzc.util.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by anyleKe on 2016/2/1.
 */
@Controller
@RequestMapping("/")
public class PictureController {

    private static Logger log = LoggerFactory.getLogger(PictureController.class);

    private String avatarSaveFolder = "images";

    @Autowired
    MemberService memberService;

    @ResponseBody
    @RequestMapping(value = "/avatar", method = RequestMethod.POST)
    public Result updateAvatar(@RequestParam String qtoken, @RequestParam("avatar") MultipartFile avatar) {

        // 保存文件
        File folder = new File(avatarSaveFolder);

        if (!folder.exists()) {
            folder.mkdirs();
        }
        // 获得扩展名
//        String fileName = getAvatarFileName(avatar.getOriginalFilename());
        String fileName = avatar.getOriginalFilename();
        File saveFile = new File(folder, fileName);

        try {
            IOUtils.copy(avatar.getInputStream(), new FileOutputStream(saveFile));
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Result.ERROR, "头像上传失败");
        }

        String url = "/" + fileName;
        // 更新数据库
        memberService.updateAvatar(url, qtoken);

        System.out.println(memberService.queryInfo(qtoken).getAvatar());
        // 返回头像地址
        return new Result(Result.SUCCESS, memberService.queryInfo(qtoken));
    }


    @ResponseBody
    @RequestMapping(value = "/images/{name}.{extension}")
    public ResponseEntity<byte[]> downloadImage(@PathVariable String name, @PathVariable String extension) throws IOException {
        String realPath = String.format("%s/%s.%s", avatarSaveFolder, name, extension);
        return handleDownload(realPath, extension);
    }

    public ResponseEntity<byte[]> handleDownload(String realPath, String extension) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        String fileName = String.format("%s.%s", UUID.randomUUID().toString(), extension);
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        File file = new File(FileUtils.path(realPath));
        if (!file.exists()) {
            log.error(String.format("文件[%s]不存在", realPath));
            return null;
        }
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }

    /**
     * 切割文件名，重新命名
     * @param uploadFileName
     * @return
     */
    public static String getAvatarFileName(String uploadFileName) {
        String fileExtension = uploadFileName.substring(uploadFileName.lastIndexOf("."));

        String name = UUID.randomUUID().toString() + fileExtension;

        return name;
    }


    /**
     * 客户端上传图片
     *返回图片位置
     * @param file
     * @return
     */
//    @ResponseBody
//    @RequestMapping("/upload")
//    public Result uploadHeadPic(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
//        String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//        String fileName = String.format("%s%s", UUID.randomUUID().toString(), extension);
//
//        System.out.println(request.getRealPath(request.getContextPath()+"/images"));
//
////        String fullDirectory = String.format("%s/images", uploadFolder);//完整目录名
//        String fullDirectory = "images";//完整目录名
//        String filePath = "";
//        String fullFilePath = String.format("%s/%s", fullDirectory, fileName);
//        System.out.println("fullFilePath: "+fullFilePath);
//
//
//        //创建文件夹
//        FileUtils.createDirectory(fullDirectory);
//
//        try {
//            String baseDirectory = String.format("/images");//基本目录名
//            File tFile = new File(fullFilePath);
//            FileOutputStream ous = new FileOutputStream(tFile);
//            IOUtils.copy(file.getInputStream(), ous);
//            filePath = String.format("%s/%s", baseDirectory, fileName);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return new Result(200, filePath, "upload success");
//    }

}
